import c_extends from "../extends"
interface options {
  type?: number
  duration?: number
  frequency?: number
}
enum throttleType {time, frequency}
class Throttle {
  onCount: boolean = false
  count: number = 0
  isFirst = true
  timeId: any
  duration: number = 0
  frequency: number = 0
  type: number = throttleType.time
  callBack: Function
  constructor (fun: Function, {type = throttleType.time, duration = 250, frequency = 10}) {
    c_extends(this, {type, duration, frequency})
    this.callBack = fun
  }
  // 时间类型节流阀
  timeTypeThrottle = () => {
    if (this.isFirst) {
      this.isFirst = false
      return this.callBack()
    }
    if (this.onCount) return
    this.onCount = true
    this.timeId = setTimeout(() => {
      this.callBack()
      this.onCount = false
      clearTimeout(this.timeId)
    }, this.duration);
  }

  // 频率类型节流阀
  frequencyTypeThrottle = () => {
    if (this.isFirst) {
      this.isFirst = false
      this.callBack()
      return
    }
    if (this.count < this.frequency) {
      this.count++
      return
    }
    this.callBack()
    this.count = 0
  }
}

function throttle (fun: Function, options?: options) {
  let thr = new Throttle(fun, options ? options : {})
  if (thr.type === throttleType.time) {
    return thr.timeTypeThrottle
  } else {
    return thr.frequencyTypeThrottle
  }
}

export {Throttle}
export default throttle
